package com.hqyj.shiro;

import com.hqyj.dao.EmployeeMapper;
import com.hqyj.dao.UserMapper;
import com.hqyj.pojo.Employee;
import com.hqyj.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    UserMapper Umapper;

    @Autowired
    EmployeeMapper Emapper;

    //权限校验
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //登录校验（包含了用户与员工的登录）
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取令牌
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        //取出用户账号
        String userNumber = token.getPrincipal()+"";
        //验证用户账号是否正确
        User user = Umapper.selectByUserName(userNumber);
        Employee employee = Emapper.selectByEmployeeName(userNumber);
        //用户的密码校验
        if(user!=null){
            //密码验证 (查询到的用户名，密码，自己写的盐值，当前这个类的名字)
            AuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getuPassword(),new Md5Hash(userNumber),this.getName());
            return info;
        }else if(employee!=null){
            //密码验证 (查询到的用户名，密码，自己写的盐值，当前这个类的名字)
            AuthenticationInfo info = new SimpleAuthenticationInfo(employee,employee.getEmployeePassword(),new Md5Hash(userNumber),this.getName());
            return info;
        }else {
            //抛出用户名不存在的异常
            throw new UnknownAccountException();
        }

    }

}
